<template>
  <el-card class="user-monitor-container">
    <el-row :gutter="40" class="user-link-monitor-content">
      <el-col :span="12">
        <el-form :model="monitorData.queryForm" class="task-search-form" ref="pluginSearchFormRef" label-position="left" @submit.native.prevent>
          <el-form-item prop="name" label="监控任务搜索">
            <el-input
              placeholder="请输入监控名称搜索"
              v-model.trim="monitorData.queryForm.name"
              @input="searchInput"
              @keyup.enter="searchTask"
            >
              <template #suffix>
                <i class="el-icon-search" @click="searchTask"></i>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12" class="btn-box">
        <el-button type="success" @click="monitorData.showTaskLog = true">查看日志</el-button>
      </el-col>
      <el-col class="operate-box">
        <el-dropdown v-for="item in monitorData.operate" :key="item.title" trigger="click">
          <el-button :type="item.btnType" size="mini" plain>
            {{ item.title }}<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-tooltip
                effect="light"
                placement="right"
                v-for="drop in item.dropDown"
                :key="drop.name"
                popper-class="more-tooltip"
                :disabled="['启用选中','停用选中','删除选中','导出选中'].includes(drop.name)">
                <el-dropdown-item :disabled="drop.disabled" @click="execute(item.title,drop,['short','code'])">
                  {{ drop.name }}
                </el-dropdown-item>
                <template #content>
                  <div class="more-operate">
                    <div class="operate-item" @click="execute(item.title,drop,['short'])">短 链</div>
                    <div class="operate-item" @click="execute(item.title,drop,['code'])">活 码</div>
                  </div>
                </template>
              </el-tooltip>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button size="small" plain class="reset-filter-btn" @click="clearFilter"
                   v-if="monitorData.queryForm.type.length>0 || monitorData.queryForm.time.length>0 || monitorData.queryForm.urlstate.length>0 || monitorData.queryForm.switch.length>0 || monitorData.queryForm.stateswitch.length>0 || monitorData.queryForm.tongzhitype.length>0 || monitorData.queryForm.project.length>0">
          重置筛选
        </el-button>
        <el-button class="add-task-btn" size="small" type="primary" @click="openTaskDialog('添加任务')">添加任务</el-button>
      </el-col>
      <el-col class="table-col-box">
        <el-table
          ref="monitorTableRef"
          :data="monitorData.tableData.data"
          @selection-change="tableSelect"
          @filter-change="tableFilter"
          v-loading="monitorData.tableLoading"
          :max-height="monitorData.tableMaxHeight"
        >
          <el-table-column type="selection" width="35px">
          </el-table-column>
          <el-table-column type="expand" width="35px">
            <template #default="scope">
              <el-descriptions column="2">
                <el-descriptions-item label="任务编号">
                  <el-tag type="primary" size="small">{{ scope.row.id }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="任务名称">
                  <el-tag type="primary" size="small">{{ scope.row.name }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="检测方式">
                  <el-tag type="primary" size="small">
                    {{ monitorData.monitorApiList.filter(item => item.interface_name === scope.row.project)[0]?.name }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="监控目标">
                  <el-link type="primary">{{ scope.row.url }}</el-link>
                </el-descriptions-item>
                <el-descriptions-item label="目标状态">
                  <el-tag type="success" size="small" v-if="scope.row.urlstate == 1">正常</el-tag>
                  <el-tag type="danger" size="small" v-else-if="scope.row.urlstate == 0">异常</el-tag>
                  <el-tag type="info" size="small" v-else>未知</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="具体原因">
                  <el-tag type="primary" size="small">{{ scope.row.urlstatemsg ? scope.row.urlstatemsg : '暂无' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="更新时间">
                  <el-tag type="primary" size="small">{{ scope.row.update_time }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="任务状态">
                  <el-tag type="success" size="small" v-if="scope.row.stateswitch == 1">已开启</el-tag>
                  <el-tag type="danger" size="small" v-else>已关闭</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="自动停用">
                  <el-tag type="success" size="small" v-if="scope.row.switch == 1">已开启</el-tag>
                  <el-tag type="danger" size="small" v-else>已关闭</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="告警方式">
                  <el-tag type="danger" size="small" v-if="scope.row.tongzhistate == 1">异常报警</el-tag>
                  <el-tag type="success" size="small" v-else>正常报警</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="监控节点">
                  <el-tag type="primary" size="small" v-if="scope.row.node == 0">自动节点</el-tag>
                  <el-tag type="success" size="small" v-else>{{ scope.row.node }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="报警通知">
                  <el-tag type="success" size="small" v-if="scope.row.tongzhiswitch == 1">已开启</el-tag>
                  <el-tag type="danger" size="small" v-else>已关闭</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="通知方式" v-if="scope.row.tongzhiswitch == 1">
                  <el-tag type="primary" size="small" v-for="item in $store.state.userStore.noticeRadio" :key="item.value" v-show="scope.row.tongzhitype == item.value">
                    {{ item.text }}通知
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="通知账户" v-if="scope.row.tongzhiswitch == 1">
                  <el-tag type="primary" size="small" v-if="['1','2','3'].includes(scope.row.tongzhitype)">
                    {{ scope.row.mail }}
                  </el-tag>
                  <el-tag type="primary" size="small" v-else-if="['5','7','8'].includes(scope.row.tongzhitype)">
                    {{ ((monitorData.allNoticeList.filter(item => item.id == scope.row.mail))[0])?.name }}
                  </el-tag>
                  <el-tag type="info" size="small" v-else>未设置</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="执行时间">
                  <el-tag type="primary" size="small" v-if="scope.row.timeswitch">
                    {{ $filter('YYYY-mm-dd HH:MM:SS', new Date(Number(scope.row.section_time.substring(1,scope.row.section_time.length-1).split(',')[0]))) }}
                    至
                    {{ $filter('YYYY-mm-dd HH:MM:SS', new Date(Number(scope.row.section_time.substring(1,scope.row.section_time.length-1).split(',')[1]))) }}
                  </el-tag>
                  <el-tag type="danger" size="small" v-else>已关闭</el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="任务名称" show-tooltip-when-overflow>
          </el-table-column>
          <el-table-column prop="type" label="类型" filter-placement="bottom"
            :filters="[
              { text:'短链',value: 'short' },
              { text:'活码',value: 'code' },
            ]">
            <template #default="scope">
              <span v-if="scope.row.type === 'short'">短链</span>
              <span v-else-if="scope.row.type === 'code'">活码</span>
            </template>
          </el-table-column>
          <el-table-column prop="project" label="检测方式" min-width="120px" filter-placement="bottom"
            :filters="monitorData.monitorApiList.map(item => ({ text:item.name, value:item.interface_name }))">
            <template #default="scope">
              {{ monitorData.monitorApiList.filter(item => item.interface_name === scope.row.project)[0]?.name }}
            </template>
          </el-table-column>
          <el-table-column prop="time" label="监控频率" min-width="105px" sortable :filters="monitorData.monitorFrequencyList" filter-placement="bottom">
            <template #default="scope">
              <span v-if="scope.row.time < 60">{{ scope.row.time }}分钟</span>
              <span v-else-if="scope.row.time >= 60 && scope.row.time < 1440">{{ scope.row.time/60 }}小时</span>
              <span v-else>{{ parseInt((scope.row.time/1440).toString()) }}天{{ (scope.row.time-1440)/60 }}小时</span>
            </template>
          </el-table-column>
          <el-table-column prop="tongzhitype" label="通知方式" :filters="$store.state.userStore.noticeRadio" filter-placement="bottom">
            <template #default="scope">
              <div class="notice-method" v-if="scope.row.tongzhiswitch == 1">
                <div :class="item.imgBgClass" v-for="item in $store.state.userStore.noticeRadio" :key="item" v-show="item.value == scope.row.tongzhitype">
                  <img :src="'/img/my-short-chain-images/short-chain-management-images/'+item.imgName+'.png'" :alt="item.imgName">
                </div>
              </div>
              <span class="iconfont icon-jinzhi" v-else></span>
            </template>
          </el-table-column>
          <el-table-column prop="urlstate" label="状态" filter-placement="bottom"
            :filters="[
              { text:'正常',value: 1 },
              { text:'异常',value: 0 },
              { text:'未知',value: 2 },
            ]">
            <template #default="scope">
              <span v-if="scope.row.urlstate == 1" class="success-text">正常</span>
              <span v-else-if="scope.row.urlstate == 0" class="danger-text">异常</span>
              <span v-else class="secondary-text">未知</span>
            </template>
          </el-table-column>
          <el-table-column prop="switch" label="自动停用" filter-placement="bottom"
            :filters="[
              { text:'已开启',value: 1 },
              { text:'已关闭',value: 0 },
            ]">
            <template #default="scope">
              <el-switch v-model="scope.row.switch" :loading="scope.row.switching" :active-value="1" :inactive-value="0" :before-change="()=>enableSwitch(scope.row,'switch',[scope.row.id])"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="stateswitch" label="启用" filter-placement="bottom"
            :filters="[
              { text:'已开启',value: 1 },
              { text:'已关闭',value: 0 },
            ]">
            <template #default="scope">
              <el-switch v-model="scope.row.stateswitch" :loading="scope.row.stateswitching" :active-value="1" :inactive-value="0" :before-change="()=>enableSwitch(scope.row,'stateswitch',[scope.row.id])"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="120px">
            <template #default="scope">
              <div class="operate-btn-group">
                <img :src="imgRootSrc+'meter_icon.png'" title="测试" alt="meter_icon" v-if="!scope.row.testing" @click="testTask(scope.row)">
                <i class="el-icon-loading" v-else></i>
                <img src="/img/table-operate-images/edit_icon.png" title="编辑" alt="edit_icon" @click="openTaskDialog('编辑任务',scope.row)">
                <img src="/img/table-operate-images/delete_icon.png" title="删除" alt="delete_icon" @click="operationTask('删除操作',[scope.row.id])">
              </div>
            </template>
          </el-table-column>
          <template #empty>
            <div class="empty-box">
              <img class="empty-img" src="/img/404-images/empty.png" alt="暂无监控任务">
              <span class="secondary-text">暂无监控任务</span>
            </div>
          </template>
        </el-table>
      </el-col>
    </el-row>
    <el-pagination
      background
      @size-change="handleSizeChange($event,'table')"
      @current-change="handleCurrentChange($event,'table')"
      :current-page="monitorData.queryForm.page"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="monitorData.queryForm.per_page"
      layout="total, sizes, prev, pager, next, jumper"
      :total="monitorData.tableData.total">
    </el-pagination>
  </el-card>

  <el-dialog :title="monitorData.dialogTitle" width="544px" v-model="monitorData.showDialog" top="40px" @closed="closeDialog('taskFormRef')" custom-class="task-form-container">
    <el-form :model="monitorData.formData" :rules="monitorData.taskFormRules" ref="taskFormRef" label-position="top">
      <el-form-item label="任务名" prop="name">
        <el-input v-model.trim="monitorData.formData.name" placeholder="若不填写，则为随机任务名">
        </el-input>
      </el-form-item>
      <el-form-item label="监控链接" prop="monitorLink">
        <el-cascader v-model="monitorData.formData.monitorLink" separator=" / " :props="{ multiple: false }" clearable :options="monitorData.monitorOption" placeholder="请选择监控链接" @change="val => monitorData.formData.type = val[0]">
        </el-cascader>
    </el-form-item>
     <el-form-item label="检测方式" prop="project">
       <el-select class="select-group" v-model="monitorData.formData.project" placeholder="请选择检测方式">
         <el-option v-for="item in monitorData.monitorApiList" :key="item.id" :label="item.name" :value="item.interface_name">
         </el-option>
       </el-select>
     </el-form-item>
      <el-row>
        <el-col :span="13">
          <el-form-item label="监控频率选择">
            <el-radio-group size="small" v-model="monitorData.monitorSelect" @change="()=>monitorData.formData.time = ''" fill="#0766FE" class="monitor-frequency-radio">
              <el-radio-button label="推荐"></el-radio-button>
              <el-radio-button label="自定义"></el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="监控频率" prop="time">
            <el-select class="select-group" v-model="monitorData.formData.time" placeholder="请选择监控频率" v-if="monitorData.monitorSelect === '推荐'">
              <el-option v-for="item in monitorData.monitorFrequencyList" :key="item.value" :label="item.text" :value="item.value">
              </el-option>
            </el-select>
            <el-input placeholder="请输入分钟" v-model.number="monitorData.formData.time" v-else>
              <template #append>分钟</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item prop="tongzhistate">
        <template #label>
          报警模式
          <span class="iconfont icon-wenti_yiwen"></span>
          <span class="msg-tips">选择监控目标在那种状态下报警</span>
        </template>
        <el-radio-group v-model="monitorData.formData.tongzhistate">
          <el-radio label="1">异常报警</el-radio>
          <el-radio label="0">正常报警</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="自动停用" prop="switch" class="switch-item">
        <el-switch v-model="monitorData.formData.switch" :active-value="1" :inactive-value="0">
        </el-switch>
        <span class="iconfont icon-wenti_yiwen"></span>
        <span class="msg-tips">根据报警模式，通知后自动停用，避免重复通知。</span>
      </el-form-item>
      <el-form-item label="报警通知" class="switch-item">
        <el-switch v-model="monitorData.formData.tongzhiswitch" active-value="1" inactive-value="0" @change="noticeChange"></el-switch>
      </el-form-item>
      <div v-if="monitorData.formData.tongzhiswitch == 1">
        <el-form-item prop="tongzhitype">
          <el-radio-group v-model="monitorData.formData.tongzhitype" @change="switchNotice" class="notice-radio">
            <el-radio v-for="item in $store.state.userStore.noticeRadio" :key="item.value" :label="item.value" :class="item.radioClass">
              <div :class="item.imgBgClass">
                <img :src="'/img/my-short-chain-images/short-chain-management-images/'+item.imgName+'.png'" :alt="item.imgName">
              </div>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="mail" ref="noticeAccountRef">
          <el-autocomplete
            v-model.trim="monitorData.formData.mail"
            :fetch-suggestions="queryNotice"
            :value-key="monitorData.formData.tongzhitype == 1 ? 'email' : 'phone'"
            :placeholder="`请输入或选择通知${monitorData.noticeName}`"
            :debounce="0"
            v-if="['1','2','3'].includes(monitorData.formData.tongzhitype)"
          >
          </el-autocomplete>
          <el-select
            class="select-group"
            default-first-option
            v-model="monitorData.formData.mail"
            :placeholder="`请选择通知${monitorData.noticeName}`"
            v-else-if="monitorData.switchingNotice || monitorData.noticeAccountList.length > 0"
          >
            <el-option
              v-for="item in monitorData.noticeAccountList"
              :key="item.id" :value="item.email" :label="item.email"
              v-if="monitorData.formData.tongzhitype == 1"
            >
            </el-option>
            <el-option
              v-for="item in monitorData.noticeAccountList"
              :key="item.id" :value="item.phone" :label="item.phone"
              v-else-if="monitorData.formData.tongzhitype == 2 || monitorData.formData.tongzhitype == 3"
            >
            </el-option>
            <el-option v-for="item in monitorData.noticeAccountList" :key="item.id" :value="(item.id).toString()" :label="item.name" v-else>
            </el-option>
          </el-select>
          <div class="notice-set" v-else>
            你当前未设置{{ monitorData.noticeName }}通知，请前往
            <el-button type="text" @click="openNoticeSet">通知账户设置</el-button>
          </div>
        </el-form-item>
      </div>
      <el-form-item label="执行时间" prop="timeswitch" class="switch-item">
        <el-switch
          v-model="monitorData.formData.timeswitch"
          :active-value="1"
          :inactive-value="0"
          @change="val=>!val ? monitorData.formData.section_time = [] : ''"
        ></el-switch>
      </el-form-item>
      <el-form-item prop="section_time" v-if="monitorData.formData.timeswitch">
        <el-date-picker
          v-model="monitorData.formData.section_time"
          type="datetimerange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        >
        </el-date-picker>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="default" :loading="monitorData.submiting" size="mini" @click="monitorData.showDialog = false">取消</el-button>
      <el-button type="primary" :loading="monitorData.submiting" size="mini" @click="monitorTaskSubmit">确定</el-button>
    </template>
  </el-dialog>

  <el-drawer custom-class="journal-drawer" v-model="monitorData.showTaskLog" @open="getTaskLog">
    <h4>最近七天监控日志</h4>
    <div class="journal-container" v-if="monitorData.taskLogList.data?.length > 0">
      <div class="journal-list" v-loading="monitorData.taskLogLoading">
        <div class="journal-list-item" v-for="item in monitorData.taskLogList.data" :key="item.id">
          <div class="journal-list-item-header">
            <h5>{{ item.project }}</h5>
            <span class="secondary-text">{{ item.time }}</span>
          </div>
          <div class="journal-list-item-text journal-list-item-link">
            监控链接：{{ item.url }}
          </div>
          <div class="journal-list-item-text journal-list-item-task">
            任务名：{{ item.name }}
          </div>
          <div class="journal-list-item-text journal-list-item-status">
            状态：
            <span class="success-text" v-if="item.state == '正常'">{{ item.state }}</span>
            <span class="danger-text" v-else-if="item.state == '异常'">{{ item.state }}</span>
            <span class="secondary-text" v-else>{{ item.state }}</span>，
            <span v-if="item.tongzhitype == 1">已发送邮箱至您的收件箱，若未收到邮件，请检查邮件垃圾箱。</span>
            <span v-if="item.tongzhitype == 2">已发送短信至您的手机，若未收到短信，请检查短信是否被拦截。</span>
            <span v-if="item.tongzhitype == 3">已拨打您的手机，若未接受到电话，请检查来电是否被拦截。</span>
            <span v-if="item.tongzhitype == 5">已通过钉钉通知您</span>
            <span v-if="item.tongzhitype == 7">已通过企业微信通知您</span>
            <span v-if="item.tongzhitype == 8">已通过飞书通知您</span>
          </div>
        </div>
      </div>
      <el-pagination
        background
        small
        :pager-count="3"
        @size-change="handleSizeChange($event,'taskLog')"
        @current-change="handleCurrentChange($event,'taskLog')"
        :current-page="monitorData.taskLogQuery.page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="monitorData.taskLogQuery.per_page"
        layout="total, sizes, prev, pager, next, jumper"
        :total="monitorData.taskLogList.total">
      </el-pagination>
    </div>
    <div class="journal-empty" v-else>
      <img src="/img/404-images/empty.png" alt="empty">
      <span class="secondary-text">暂无监控日志</span>
    </div>
  </el-drawer>
</template>

<script setup>
import { reactive, getCurrentInstance, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { taskList, taskLog, taskAdd, cloudTask, taskEdit, selectstart, selectDel, selectStop, apilist, fallList, noticeSetList, getAllSettingList, addNotice } from '@/axios/userRequest'
import axios from 'axios'
import baseUrl from '@/axios/baseUrl'
const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()
const imgRootSrc = '/img/monitor-system-images/'

let taskForm = {// 监控任务表单
  type: '',// code（活码类型）short（短链类型）
  stateswitch: 1, // 任务开关
  name: '', // 任务名
  url: '', // 监控链接
  target: '', // 被监控的目标  短链的名称或者 活码的入口域名
  monitorLink: [], // 监控链接
  codeorshort_id: '',// 活码 或者短链的id
  api_id: '',// api id
  project: '', // 检测方式
  api_url: '',// api完整地址
  api_data: {},// api数据
  node: '自动节点', // 监控节点
  time: '', // 监控频率
  tongzhistate: '1', // 告警方式 1:异常告警  0：正常告警
  switch: 1, // 自动停用 0关闭 1开启
  tongzhiswitch: '0', // 到期通知 1开启 0关闭
  tongzhitype: '1', // 通知方式 1：邮箱，2：短信，3：手机，5：钉钉，7：企业微信，8：飞书
  mail: '',// 通知账户 邮箱或手机的时候传邮箱或手机号，其他的时候传id
  callbackurlswitch: 0,// 回调地址开关
  callbackurl:'', // 回调地址
  callbackurl_type: 0,// 回调方式 0=GET,1=POST
  timeswitch: 0, // 执行时间段开关
  section_time: [],// 通知时间
}
let queryData = {// 查询监控列表参数
  page: 1,// 页码
  per_page: 5,// 每页显示数量
  name: '',// 搜索名称
  type: [],// 任务类型
  time: [],// 监控频率
  urlstate: [],// 任务链接状态
  switch: [],// 自动停用开关
  stateswitch: [],// 启用开关
  tongzhitype: [],// 通知类型
  project: [],// 检测方式
}
// 监控系统数据
let monitorData = reactive({
  showDialog: false,// 添加或编辑任务对话框
  tableLoading: false,// 表格加载
  submiting:false,// 提交中
  dialogTitle: '添加任务',// 对话框标题
  switchingNotice: true,// 切换通知账户中
  showTaskLog: false,// 查看日志
  taskLogLoading: false,// 日志加载中
  taskLogList:[],// 日志列表
  tableMaxHeight: window.innerHeight - 371,// 表格最高高度
  taskLogQuery:{// 查询日志参数
    page: 1,// 页码
    per_page: 5,// 每页显示数量
  },
  tableData:[],// 监控表格数据
  shortLinkData: {},// 短链数据
  liveCodeData: {},// 活码数据
  filterData:[],// 监控表格过滤
  showFilterBtn: false,// 重置过滤按钮
  monitorOption: [// 监控链接选项
    {
      label: '短链',
      value: 'short',
      children: [
        { value: 3, label: '入口域名', children: [] },
        { value: 5, label: '落地域名', children: [] },
      ]
    },
    {
      label: '活码',
      value: 'code',
      children: [
        { value: 1, label: '入口域名', children: [] },
        { value: 2, label: '落地域名', children: [] },
      ]
    }
  ],
  monitorApiList: [],// 检测方式列表
  allNoticeList:[],// 所有的通知方式
  monitorFrequencyList: [// 监控频率列表
    { text:'30分钟', value: 30 },
    { text:'1小时', value: 60 },
    { text:'3小时', value: 180 },
    { text: '6小时', value: 360 },
    { text: '12小时', value: 720 },
    { text: '1天', value: 1440 },
  ],
  monitorSelect: '推荐',// 选择检测方式切换按钮
  noticeName: '邮箱', // 通知方式名字
  noticeAccountList: [],// 通知账户列表
  selectId: [],// 选中的任务id
  formData: JSON.parse(JSON.stringify(taskForm)),
  queryForm: JSON.parse(JSON.stringify(queryData)),
  taskFormRules:{//表单验证规则
    monitorLink: [{ required: true, message: '请选择监控链接' }],
    project: [{ required: true, message: '请选择检测方式' }],
    time:[
      { required: true, message: '监控频率不能为空' },
      { type: 'number', message: '监控频率必须为正整数' },
    ],
    tongzhistate: [{ required: true, message:'请选择报警模式' }],
    tongzhitype: [{ required: true, message: '请选择通知渠道' }],
    mail: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if(!value) return callback('请输入或选择通知账户')
          let emailreg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
          let phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
          if (monitorData.formData.tongzhitype == 1 && !emailreg.test(value)){
            callback(new Error('请输入正确邮箱号'))
          }else if((monitorData.formData.tongzhitype == 2 || monitorData.formData.tongzhitype == 3) && !phoneReg.test(value)) {
            callback(new Error('请输入正确的手机号'))
          }else{
            callback()
          }
        }
      }
    ],
    section_time: [{ required: true, message: '请选择执行时间' }],
  },
  operate:[
    {
      title:'启用操作',
      btnType:'success',
      showDropDown: false,
      dropDown:[
        { name: '启用选中', api:'' },
        { name: '启用全部', api:'/allstart' },
        { name: '启用异常', api:'/startabnormal' },
        { name: '启用正常', api:'' },
        { name: '启用未知', api:'' },
      ]
    },
    {
      title:'停用操作',
      btnType:'danger',
      showDropDown: false,
      dropDown:[
        { name: '停用选中', api:'' },
        { name: '停用全部', api:'' },
        { name: '停用异常', api:'/stopabnormal' },
        { name: '停用正常', api:'/stopnormal' },
        { name: '停用未知', api:'' },
      ]
    },
    {
      title:'删除操作',
      btnType:'warning',
      showDropDown: false,
      dropDown:[
        { name: '删除选中', api:'' },
        { name: '删除全部', api:'/delall' },
        { name: '删除停用', api:'/delstop' },
        { name: '删除启用', api:'/delstart' },
        { name: '删除异常', api:'/delabnormal' },
        { name: '删除正常', api:'/delnormal' },
        { name: '删除未知', api:'' },
        { name: '删除过期', api:'' },
      ]
    },
    {
      title:'导出操作',
      btnType:'primary',
      showDropDown: false,
      dropDown:[
        { name: '导出选中', api:`${baseUrl}/api/execl?type=select&id=` },
        { name: '导出全部', api:`${baseUrl}/api/execl?type=all` },
        { name: '导出启用', api:`${baseUrl}/api/execl?type=enable` },
        { name: '导出停用', api:`${baseUrl}/api/execl?type=outservice` },
        { name: '导出异常', api:`${baseUrl}/api/execl?type=abnormal` },
        { name: '导出正常', api:`${baseUrl}/api/execl?type=normal` },
        { name: '导出未知', api:`${baseUrl}/api/execl?type=unknown` },
        { name: '导出过期', api:`${baseUrl}/api/execl?type=overdue` },
      ]
    },
  ],
})
const resizeHeight = ()=>monitorData.tableMaxHeight = window.innerHeight - 371
onMounted(()=>window.addEventListener('resize',resizeHeight))
onUnmounted(()=>window.removeEventListener('resize',resizeHeight))
// 获取监控列表
const getTaskList = async ()=>{
  monitorData.tableLoading = true
  const res = await taskList(monitorData.queryForm)
  if(res.code === 0) {
    monitorData.tableData = res.data[0]
    monitorData.tableLoading = false
    if(res.data[0].total > 0){
      for (let i = 0; i < monitorData.operate.length; i++) {
        monitorData.operate[i].dropDown.forEach(item => item.name.substring(2) === '选中' ? item.disabled = true : '')
      }
    }
  }else{
    proxy.$message.error(res.msg)
  }
}
// 获取日志列表
const getTaskLog = async ()=>{
  monitorData.taskLogLoading = true
  const res = await taskLog(monitorData.taskLogQuery)
  if(res.code === 0){
    monitorData.taskLogList = res.data
    monitorData.taskLogLoading = false
  }else{
    proxy.$message.error(res.msg)
  }
}
// 获取检测api，短链分组和列表
const getData = async ()=>{
  const res = await axios.all([apilist(), getAllSettingList(), fallList({ type:[3,5] }), fallList({ type:[1,2] })])
  res[0].code === 0 ? monitorData.monitorApiList = res[0].data : proxy.$message.error(res[0].msg)
  res[1].code === 0 ? monitorData.allNoticeList = res[1].data : proxy.$message.error(res[1].msg)
  // 短链选项
  if(res[2].code === 0){
    monitorData.shortLinkData = res[2].data.data
    monitorData.monitorOption[0].children[0].children = res[2].data.data[3].map(item=>({ value: item.id, label: item.domain }))
    monitorData.monitorOption[0].children[1].children = res[2].data.data[5].map(item=>({ value: item.id, label: item.domain }))
  }else{
    proxy.$message.error(res[2].msg)
  }
  // 活码选项
  if(res[3].code === 0){
    monitorData.liveCodeData = res[3].data.data
    monitorData.monitorOption[1].children[0].children = res[3].data.data[1].map(item=>({ value: item.id, label: item.domain }))
    monitorData.monitorOption[1].children[1].children = res[3].data.data[2].map(item=>({ value: item.id, label: item.domain }))
  }else{
    proxy.$message.error(res[3].msg)
  }
}
getTaskList()
getData()
// 查询内容改变时
let timer = null
const searchInput = val=>{
  monitorData.queryForm.name = val
  if(val){
    clearTimeout(timer)
    timer = setTimeout(()=> getTaskList(),500)
  }else{
    getTaskList()
  }
}
// 搜索任务
const searchTask = ()=> monitorData.queryForm.name ? getTaskList() : proxy.$message.warning('请输入监控名称')
// 修改通知类型
const updateNoticeName = type=>{
  type == 1 ? monitorData.noticeName = '邮箱' : ''
  type == 2 || type == 3 ? monitorData.noticeName = '手机' : ''
  type == 5 ? monitorData.noticeName = '钉钉' : ''
  type == 7 ? monitorData.noticeName = '企业微信' : ''
  type == 8 ? monitorData.noticeName = '飞书' : ''
  // 查询通知方式
  monitorData.noticeAccountList = []
  monitorData.switchingNotice = true
  noticeSetList({ type: monitorData.noticeName }).then(res => {
    if(res.code === 0){
      monitorData.noticeAccountList = res.data.data
      monitorData.switchingNotice = false
    }else{
      proxy.$message.error(res.msg)
    }
  }).catch(err=>{})
}
// 到期通知开关
const noticeChange = val => val ? updateNoticeName(monitorData.formData.tongzhitype) : proxy.$refs.noticeAccountRef.resetField()
// 邮箱短信手机查询通知
const queryNotice = (queryString, cb) => cb(monitorData.noticeAccountList.length > 0 ? monitorData.noticeAccountList : [])
// 切换通知渠道
const switchNotice = notice => {
  proxy.$refs.noticeAccountRef.resetField()
  monitorData.formData.mail = ''
  updateNoticeName(notice)
}
// 打开通知账户设置
const openNoticeSet = ()=>{
  router.push('/user-center/user-account/user-setting')
  localStorage.setItem('switchTabSet','noticeSet')
  localStorage.setItem('activeName',monitorData.noticeName)
}
// 打开添加或编辑对话框
const openTaskDialog = (title, row={})=>{
  monitorData.dialogTitle = title
  monitorData.showDialog = true
  if(title === '编辑任务'){
    monitorData.monitorSelect = '自定义'
    monitorData.formData = JSON.parse(JSON.stringify(row))
    monitorData.formData.time = Number(monitorData.formData.time)
    monitorData.formData.tongzhiswitch == 1 ? updateNoticeName(monitorData.formData.tongzhitype) : ''
    switch (monitorData.formData.type) {
      case 'short':
        let short = (Object.values(monitorData.shortLinkData).flat()).filter(item => monitorData.formData.codeorshort_id === item.id)[0]
        monitorData.formData.monitorLink = [monitorData.formData.type, short.domain_type, short.id]
        break
      case 'code':
        let code = (Object.values(monitorData.liveCodeData).flat()).filter(item => monitorData.formData.url === item.domain)[0]
        monitorData.formData.monitorLink = [monitorData.formData.type, code.domain_type, code.id]
        break
    }
    if(monitorData.formData.timeswitch == 1){
      let sectionTime = monitorData.formData.section_time.substring(1,monitorData.formData.section_time.length-1).split(',')
      monitorData.formData.section_time = [new Date(Number(sectionTime[0])), new Date(Number(sectionTime[1]))]
    }
  }else{// 添加任务
    monitorData.monitorSelect = '推荐'
  }
}
// 添加和编辑监控任务
const monitorTaskSubmit = ()=>{
  proxy.$refs.taskFormRef.validate(validate=>{
    if(validate){
      monitorData.submiting = true
      monitorData.formData.codeorshort_id = monitorData.formData.monitorLink[2]
      monitorData.formData.section_time = monitorData.formData.timeswitch ? monitorData.formData.section_time.map(item => Date.parse(proxy.$filter('YYYY-mm-dd HH:MM:SS',item))) : []
      monitorData.monitorApiList.filter(item => {
        if(item.interface_name ===  monitorData.formData.project){
          let index = item.api.indexOf('?')
          monitorData.formData.api_url = item.api.substring(0,index !== -1 ? index : item.api.length)
        }
      })
      switch (monitorData.formData.type) {
        case 'short':
          (Object.values(monitorData.shortLinkData).flat()).filter(item => {
            if(monitorData.formData.codeorshort_id === item.id){
              monitorData.formData.target = item.domain
              monitorData.formData.url = item.domain
              monitorData.formData.api_data = {
                token: monitorData.monitorApiList[0].token,
                url: item.domain
              }
            }
          })
          break
        case 'code':
          let url = monitorData.liveCodeData[monitorData.formData.monitorLink[1]].filter(item => item.id === monitorData.formData.codeorshort_id ? item.domain : '')
          monitorData.formData.url = monitorData.formData.target = url[0].domain
          break
      }
      if(['1','2','3'].includes(monitorData.formData.tongzhitype)){
        monitorData.noticeName === '邮箱' ? addNotice({type: monitorData.noticeName, email: [monitorData.formData.mail]}) : ''
        monitorData.noticeName === '手机' || monitorData.noticeName === '短信' ? addNotice({type: monitorData.noticeName, phone: [monitorData.formData.mail]}) : ''
      }
      monitorData.monitorApiList.forEach(item => monitorData.formData.project === item.interface_name ? monitorData.formData.api_id = item.id : '')
      let taskApi = monitorData.dialogTitle === '添加任务' ?  taskAdd : taskEdit
      taskApi(monitorData.formData).then(res=>{
        if(res.code === 0){
          proxy.$message.success(res.msg)
          monitorData.showDialog = false
          getTaskList()
        }else{
          proxy.$message.error(res.msg)
          monitorData.submiting = false
        }
      }).catch(err=>{})
    }
  })
}
// 表格过滤
const tableFilter = filters=>{
  let title = document.querySelector(`.${Object.keys(filters)[0]} .cell`).innerText
  let filterList = Object.values(Object.values(filters)[0])
  title === '检测方式' ? monitorData.queryForm.project = filterList : ''
  title === '类型' ? monitorData.queryForm.type = filterList : ''
  title === '监控频率' ? monitorData.queryForm.time = filterList : ''
  title === '通知方式' ? monitorData.queryForm.tongzhitype = filterList : ''
  title === '状态' ? monitorData.queryForm.urlstate = filterList : ''
  title === '自动停用' ? monitorData.queryForm.switch = filterList : ''
  title === '启用' ? monitorData.queryForm.stateswitch = filterList : ''
  getTaskList()
}
// 清除过滤
const clearFilter = ()=>{
  proxy.$refs.monitorTableRef.clearFilter()
  proxy.$refs.monitorTableRef.clearSort()
  monitorData.queryForm = JSON.parse(JSON.stringify(queryData))
  getTaskList()
}
// 表格行选择变化时
const tableSelect = data=>{
  monitorData.selectId = data.length > 0 ? data.map(item=>item.id) : []
  for (let i = 0; i < monitorData.operate.length; i++) {
    monitorData.operate[i].dropDown[0].disabled = data.length <= 0
  }
}
// 执行操作
const execute = async (title,drop,type)=>{
  if(monitorData.selectId.length > 0 && ['启用选中','停用选中','删除选中','导出选中'].includes(drop.name)){
    operationTask(title, monitorData.selectId)
  }else{
    proxy.$confirm(`是否确认${ drop.name }的${ type.length === 1 ? type[0] === 'short' ? '短链' : '活码' : ''}监控任务？`,title,{
      closeOnClickModal:false,
      customClass:'commonMessageBox',
      type: 'warning',
    }).then(async ()=>{
      if(drop.name.substring(0,2) !== '导出'){
        const { data:res } = await axios.get(`${baseUrl}/api${drop.api}`,{ params: { type }})
        if(res.code === 0){
          proxy.$message.success(res.msg)
          await getTaskList()
        }else{
          proxy.$message.error(res.msg)
        }
      }else{
        window.open(`${drop.api}&task_type=${type}`)
      }
    }).catch(err=>{})
  }
}
// 操作选中任务的公共方法
const operationTask = (type,id)=>{
  proxy.$confirm(`是否确认${type.substring(0,2)}${id.length > 1 ? '这些' : '这个'}监控任务？`,type,{
    closeOnClickModal:false,
    customClass:'commonMessageBox',
    type: 'warning',
  }).then(async ()=> {
    let api
    type === '启用操作' ? api = selectstart : ''
    type === '停用操作' ? api = selectStop : ''
    type === '删除操作' ? api = selectDel : ''
    if(type !== '导出操作' && api){
      api({ id }).then(res=>{
        if(res.code === 0){
          proxy.$message.success(res.msg)
          getTaskList()
        }else{
          proxy.$message.error(res.msg)
        }
      }).catch(err=>{})
    }else{
      window.open(monitorData.operate[3].dropDown[0].api+id)
    }
  }).catch(err=>{})
}
// 启动和自动停用开关
const enableSwitch = (row,type,id)=>{
  return new Promise(async (resolve,reject)=>{
    let request
    if(type === 'switch'){
      row.switching = true
      request = row.switch ? '/abnormalstop' : '/abnormalstart'
    }else{
      row.stateswitching = true
      request = row.stateswitch ? '/selectstop' : '/selectstart'
    }
    const { data:res } = await axios.get(`${baseUrl}/api${request}`,{ params:{id} })
    if(res.code === 0){
      proxy.$message.success(res.msg)
      resolve(true)
    }else{
      proxy.$message.error(res.msg)
      reject(false)
    }
    type === 'switch' ? row.switching = false : row.stateswitching = false
  })
}
// 测试任务
const testTask = async row=>{
  row.testing = true
  const res = await cloudTask({ id: row.id })
  if(res.code === 0){
    proxy.$message.success(res.data.msg)
    row.testing = false
    row.urlstate = res.data.state
    row.urlstatemsg = res.data.msg
    row.stateswitch = res.data.stateswitch
    row.update_time = res.data.update_time
  }else{
    proxy.$message.error(res.msg)
    row.testing = false
  }
}
// 切换每页数量
const handleSizeChange = (val,type)=>{
  if(type === 'table'){// 切换表格每页显示数量
    monitorData.queryForm.page = 1
    monitorData.queryForm.per_page = val
    getTaskList()
  }else if(type === 'taskLog'){// 切换日志每页数量
    monitorData.taskLogQuery.page = 1
    monitorData.taskLogQuery.per_page = val
    getTaskLog()
  }
}
// 切换页码
const handleCurrentChange = (val,type)=>{
  if(type === 'table'){// 切换表格页码
    monitorData.queryForm.page = val
    getTaskList()
  }else if(type === 'taskLog'){// 切换日志页码
    monitorData.taskLogQuery.page = val
    getTaskLog()
  }
}
// 关闭对话框重置表单
const closeDialog = refName => {
  proxy.$refs[refName].resetFields()
  if(refName === 'taskFormRef'){
    monitorData.submiting = false
    monitorData.formData = JSON.parse(JSON.stringify(taskForm))
  }
}
</script>

<style lang="less" scoped>
.user-monitor-container{
  min-height: calc(100vh - 108px);
  border-radius: 52px 12px 12px 12px;
  overflow: auto;
  &:deep(.el-card__body){
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: calc(100vh - 108px);
    padding: 40px 28px 30px;
    box-sizing: border-box;
    .user-link-monitor-content{
      display: flex;
      .el-col{
        height: inherit;
        .task-search-form {
          .el-form-item {
            .el-form-item__label {
              font-size: 16px;
              font-weight: 400;
              color: @title;
            }

            .el-form-item__content {
              display: flex;
              align-items: center;

              .el-input {
                width: 100%;
                margin-left: 15px;
              }
            }
          }
        }
      }
      .btn-box{
        display: flex;
        .el-button{
          width: 100px;
          height: 40px;
        }
      }
      .operate-box{
        margin-top: 20px;
        .reset-filter-btn,
        .el-dropdown{
          width: 100px;
          margin-right: 20px;
          position: relative;
          .el-button{
            width: inherit;
          }
        }
        .add-task-btn{
          width: 100px;
          float: right;
        }
      }
      .table-col-box{
        margin-top: 32px;
        .el-table{
          .cell{
            line-height: unset;
            .icon-jinzhi{
              font-size: 25px;
              color: @primary;
            }
          }
          .el-table__row{
            height: 65px;
          }
          .operate-btn-group{
            display: flex;
            align-items: center;
            justify-content: space-between;
            img{
              cursor: pointer;
            }
            i.el-icon-loading{
              font-size: 20px;
            }
          }
          .el-table__expanded-cell{
            .el-descriptions{
              .el-descriptions__body{
                td{
                  border: none;
                  .el-descriptions__label{
                    width: 90px;
                    display: inline-block;
                  }
                  .el-descriptions__content{
                    .el-link{
                      font-size: 13px;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>

<style lang="less">
.task-form-container {
  .el-dialog__body {
    height: 60vh;
    overflow: auto;
    .el-form{
      .el-form-item{
        .el-form-item__content{
          .el-cascader,
          .select-group,
          .el-date-editor,
          .el-autocomplete{
            width: 100%;
          }
          .notice-set{
            display: flex;
            align-items: center;
            line-height: unset;
            color: @subtitle;
            div{
              line-height: unset;
            }
            .el-button{
              min-height: unset;
            }
          }
          .el-textarea__inner {
            height: 96px !important;
          }
          .monitor-frequency-radio{
            .el-radio-button{
              .el-radio-button__inner{
                width: 90px;
              }
              &:nth-of-type(1){
                .el-radio-button__inner{
                  border-radius: 15px 0 0 15px;
                }
              }
              &:nth-of-type(2){
                .el-radio-button__inner{
                  border-radius: 0 15px 15px 0;
                }
              }
            }
          }
        }
      }
      .switch-item{
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        .el-form-item__content{
          margin-left: 15px;
          display: flex;
          align-items: center;
          line-height: unset;
          .msg-tips{
            height: 18px;
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }
}
.more-tooltip{
  padding: 0!important;
  min-width: 0!important;
  &:deep(.more-operate){
    padding: 10px;
  }
  .operate-item{
    cursor: pointer;
    padding: 5px 15px;
    font-size: 14px;
    color: #606266;
    box-sizing: border-box;
    &:hover{
      background-color: #ecf5ff;
      color: #66b1ff;
    }
  }
}

.journal-drawer{
  .el-drawer__body{
    position: relative;
    h4{
      font-size: 18px;
      color: @title;
      margin: 0 0 20px;
    }
    .journal-empty{
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      position: absolute;
      top: 40%;
      left: 50%;
      transform: translate(-50%,-50%);
      span{
        margin-top: 50px;
      }
    }
    .journal-container{
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .journal-list{
        height: calc(100vh - 240px);
        overflow: auto;
        padding-right: 20px;
        .journal-list-item{
          padding: 20px 0;
          box-sizing: border-box;
          border-bottom: 1px solid #F3F5FA;
          .journal-list-item-header{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            h5{
              font-size: 16px;
              color: @primary;
              margin: 0;
            }
            span{
              font-size: 12px;
            }
          }
          .journal-list-item-text{
            height: 18px;
            font-size: 12px;
            font-weight: 400;
            color: @subtitle;
            line-height: 18px;
            &:not(:nth-last-of-type(1)){
              margin-bottom: 4px;
            }
          }
        }
      }
    }
    .el-pagination{
      .el-select{
        .el-input{
          width: 90px;
          margin: 0;
        }
      }
    }
  }
}
</style>
